package com.ct.musicserver.controller;

import com.ct.musicserver.common.errorcode.ControllerErrorCodeConstants;
import com.ct.musicserver.common.exception.ControllerException;
import com.ct.musicserver.common.pojo.CommonResult;
import com.ct.musicserver.common.utils.Constant;
import com.ct.musicserver.common.utils.JacksonUtil;
import com.ct.musicserver.controller.param.UserLoginParam;
import com.ct.musicserver.controller.result.UserLoginResult;
import com.ct.musicserver.service.UserService;
import com.ct.musicserver.service.dto.UserLoginDTO;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpSession;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@Slf4j
@RestController
public class UserController {

    @Autowired
    private UserService userService;
    @Autowired
    private HttpSession session;


    /**
     * 登录
     *
     * @param param
     * @return
     */
    @RequestMapping("/user/login")
    public CommonResult<UserLoginResult> login (
            @Validated UserLoginParam param) {
        log.info("login UserLoginParam:{}",
                JacksonUtil.writerValueAsString(param));
        UserLoginDTO userLoginDTO = userService.login(param);
        return CommonResult.success(convertToUserLoginResult(userLoginDTO), "登录成功!");
    }

    private UserLoginResult convertToUserLoginResult(UserLoginDTO userLoginDTO) {
        if (null == userLoginDTO) {
            throw new ControllerException(ControllerErrorCodeConstants.LOGIN_ERROR);
        }
        UserLoginResult result = new UserLoginResult();
        result.setId(userLoginDTO.getId());
        result.setUsername(userLoginDTO.getUsername());
        result.setPassword(userLoginDTO.getPassword());
        session.setAttribute(Constant.USERINFO_SESSION_KEY, result);
        return result;
    }
}
